
#ifndef MouseAndCat_Serializer_h
#define MouseAndCat_Serializer_h

#include "Types.h"

class Serializer
{
    
public:
    
    template <typename an_integer>
    static int SerializeInt(an_integer, unsigned char*);
    
    template <typename an_integer>
    static int DeserializeInt(const unsigned char*, an_integer*);
};



template <typename an_integer>
int Serializer::SerializeInt(an_integer the_integer, unsigned char* buffer)
{
    int length = sizeof(an_integer);
    int move = length * 8;
    abyte byte_value;
    
    for(int i = 0; i < length; i++)
    {
        move -= 8;
        byte_value = (the_integer >> move) & 0xFF;
		*buffer++ = byte_value;
        printf("Set byte %d to %d\n", i, *(buffer - 1));
    }
    
    return length;
}


template <typename an_integer>
int Serializer::DeserializeInt(const unsigned char* buffer, an_integer* the_integer)
{
    uint8_t position = 0;
	uint8_t move = sizeof(an_integer) * 8;
    *the_integer = 0;
    an_integer byte_value;
    
    while(position++ < sizeof(an_integer))
    {
		move -= 8;
        byte_value = *buffer++ << move;
		*the_integer += byte_value;
	}
    
    if(sizeof(an_integer) == 2)
        printf("Deserialized short: %hd\n", (uint16_t)*the_integer);
    return --position;
}

#endif
